package com.cci.kangdao.service.impl;


import com.cci.kangdao.dao.CompanyTDao;
import com.cci.kangdao.dao.LoginDao;
import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.WeChatGetMaterialDao;
import com.cci.kangdao.dao.model.CompanyT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.service.WeChatGetMaterialService;
import com.cci.kangdao.utilTool.AESTool;
import com.cci.kangdao.utilTool.ParameterTool;
import com.cci.kangdao.utilTool.PropertiesUtil;
import com.cci.kangdao.utilTool.StringToool;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


//微信公众号素材类
@Service("WeChatGetMaterialService")
public class WeChatGetMaterialServiceImpl implements WeChatGetMaterialService {

	private Logger log = Logger.getLogger(this.getClass().getName());
	
	@Autowired
	private WeChatGetMaterialDao weChatGetMaterialDao;
	@Autowired
	private LoginDao loginDao;
	@Autowired
	private UserTDao userTDao;
	@Autowired
	private CompanyTDao companyTDao;

	//分页获取微信公众号素材接口
	@Transactional
	@Override
	public ModelAndView getWeChatGetMaterialList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		List<Map<String, Object>> weChatGetMaterialList = new ArrayList<>();
		String companyIds="";
		String userid = request.getHeader("userid");
		if(null != userid && !"".equals(userid)){  //代表用户是登录状态
			String userId = AESTool.decryptString(request.getHeader("userid"));//解密userid
			if(!NumberUtils.isDigits(userId)){
				log.warn("请求userId非法，抛出token错误,userId："+userId);
				ParameterTool.writeErrorResponse(response, -1);
				return null;
			}
			UserT userT = loginDao.getUserByid(userId);
//		0	Engine Customer
//		1	康明斯
//		3	JV
//		4	OEM
//		5	SSOEM
//		6	Dealer
			if(null != userT){
				Map<String,Object> userGroupMap = userTDao.getUsergroupbyUserId(userT.getId());
				if(MapUtils.isNotEmpty(userGroupMap)){
                    int isType = MapUtils.getIntValue(userGroupMap, "IsType", 0);
					if(isType == 0 || isType == 4 || isType == 5){  //用户组类型是普通用户，OEM，SSOEM用户只能看到CCI的微信公众号素材
						companyIds="1";
					}else if(isType == 1 || isType == 3){  //用户组类型是康明斯，JV只能看到自己企业下的微信公众号素材
						companyIds = String.valueOf(userT.getCompanyId());
                        if ("122".equals(companyIds)) {    //安徽康明斯同时看到康明斯和安徽康明斯微信公众号   2.7.0需求
                            companyIds = "122,1";
                        }
					}else if(isType == 6){  //用户组类型是服务站只能看到本服务站授权渠道的微信公众号素材，多个授权渠道的根据时间排序
                        int isHasACPL = 0;  //服务站是否被安徽康明斯授权(0：否   1：是)
						List<Map<String,Object>> serviceChannelList = companyTDao.getServiceChannelByStationId(userT.getServiceStationID());
						int index = 1;
						if(CollectionUtils.isNotEmpty(serviceChannelList)){
							for(Map<String,Object> serviceChannel : serviceChannelList){
                                String serviceChannelId = MapUtils.getString(serviceChannel, "ID", "");
                                if ("122".equals(serviceChannelId)) {
                                    isHasACPL = 1;
                                }
								if(index<serviceChannelList.size()){
                                    companyIds += serviceChannelId + ",";
								}else{
                                    companyIds += serviceChannelId;
								}
								index ++;
							}
                            if (isHasACPL == 1) {   //被安徽康明斯授权   则企业id带上康明斯
                                companyIds += ",1";
                            }
						}else{
							companyIds="1";
						}
					}
				}
			}else{
				companyIds="1";
				log.error("userId:"+userId+"在数据库中未查询到该用户");
			}
		}else{   //代表用户是未登录状态
			companyIds="1";
		}
		int pageNo = 1;
		int pageCount=20;
		if(null != map.get("pageNo")){
			pageNo = Integer.parseInt(map.get("pageNo").toString());
        }
        if (null != map.get("pageCount")) {
            pageCount = Integer.parseInt(map.get("pageCount").toString());
        }
        JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
        PageHelper.startPage(pageNo, pageCount);
        //如果以上面都没获取到服务渠道，这里默认查看康明斯中国的微信公众号文章(譬如重庆康明斯)
        if (StringUtils.isEmpty(companyIds)) {
            companyIds = "1";
        }
        List<String> stringList = StringToool.getStringList(companyIds, ",");
        weChatGetMaterialList = weChatGetMaterialDao.getWeChatGetMaterialList(stringList);
        if (CollectionUtils.isEmpty(weChatGetMaterialList) && pageNo == 1) {
            PageHelper.startPage(pageNo, pageCount);
            List<String> stringLists = new ArrayList<>();
            stringLists.add("1");
            weChatGetMaterialList = weChatGetMaterialDao.getWeChatGetMaterialList(stringLists);
        }
        PageInfo pageInfo = new PageInfo(weChatGetMaterialList);
        obj.put("status", 0);
        obj.put("msg", "查询成功");
        obj.put("data", pageInfo);
		ParameterTool.writeResponse(response, obj.toString());
		return null;
	}
}
